//
//  YUYAScrolImageView.m
//  com.yigu.yuya
//
//  Created by hxp on 16/3/8.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIScrolImageView.h"
#import "YAYIPageControl.h"

@interface YAYIScrolImageView()
//{
//    CGRect _frame;
//}

@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,strong) YAYIPageControl *pageControl;
@property (nonatomic,strong)NSTimer *timer;

@end

@implementation YAYIScrolImageView


/** 创建数据源
 *
 */
- (void)setImageAry:(NSArray *)imageAry
{
    
    _imageAry = imageAry;
    
    [self createImageView];
    [self createPageView];
    
    if (self.isAutoScroll) {
        [self startTimer];
    }
}


//- (void)setFrame:(CGRect)frame
//{
//    [super setFrame:frame];
//    _frame = frame;
//    self.scrollView.frame = frame;
//}


- (instancetype)init
{
    self = [super init];
    if (self) {
        _imageAry = [NSArray array];
        [self createScrollView:CGRectMake(0, 0, 0, 0)];
    }
    return self;
}


-(instancetype)initWithFrame:(CGRect)rect
{
    self = [super initWithFrame:rect];
    if (self) {
//        _frame = rect;
        _imageAry = [NSArray array];
        [self createScrollView:rect];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
//    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self);
//        make.bottom.mas_equalTo(self).offset(-7);
//        make.size.mas_equalTo(CGSizeMake(100, 20));
//    }];
}


/** 创建滚动视图
 *
 */
-(void)createScrollView:(CGRect)rect{
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:rect];
//    self.scrollView.backgroundColor = [UIColor orangeColor];
    self.scrollView.pagingEnabled = true;
    self.scrollView.showsHorizontalScrollIndicator = NO;
//    self.scrollView.bounces = NO;
    self.scrollView.alwaysBounceHorizontal = YES;
    self.scrollView.delegate = self;
    [self addSubview:self.scrollView];
}

/** 创建轮番视图
 *
 */
-(void)createImageView{
    
    // 是否无线滚动
    if (self.isAutoScroll) {
        UIImageView *imageViewFist = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width * 0, 0, self.frame.size.width, self.frame.size.height)];
        imageViewFist.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
        
        // 添加第一个imageView
        NSString *firstUrlStr = [self.imageAry lastObject];
        if ([firstUrlStr rangeOfString:@"http"].location == NSNotFound) {
            imageViewFist.image = [UIImage imageNamed:firstUrlStr];
        }else{
            [imageViewFist sd_setImageWithURL:[NSURL URLWithString:firstUrlStr] placeholderImage:[UIImage imageNamed:@"home_showImg1"] options:SDWebImageRefreshCached];
        }
        
        [self.scrollView addSubview:imageViewFist];
        
        // 添加最后一个imageView
        UIImageView *imageViewLast = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width * (self.imageAry.count + 1), 0, self.frame.size.width, self.frame.size.height)];
        
        NSString *lastUrlStr = [self.imageAry firstObject];
        if ([lastUrlStr rangeOfString:@"http"].location == NSNotFound) {
            imageViewLast.image = [UIImage imageNamed:lastUrlStr];
        }else{
            [imageViewLast sd_setImageWithURL:[NSURL URLWithString:lastUrlStr] placeholderImage:[UIImage imageNamed:@"home_showImg1"] options:SDWebImageRefreshCached];
        }
        
        [self.scrollView addSubview:imageViewLast];
    }
    
    for (int i = 0; i< self.imageAry.count; i++) {
        
        CGFloat imgX = self.isAutoScroll ? self.frame.size.width * (i + 1) : self.frame.size.width * i;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imgX, 0, self.width, self.height)];
        
        NSString *imageUrlStr = self.imageAry[i];
        YAYILog(@"url:%@", imageUrlStr);
        
        if ([imageUrlStr rangeOfString:@"http"].location == NSNotFound) {
            imageView.image = [UIImage imageNamed:imageUrlStr];
        }else{
            [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrlStr] placeholderImage:[UIImage imageNamed:@"home_showImg1"] options:SDWebImageRefreshCached];
        }
        
        [self.scrollView addSubview:imageView];
    }
    
    if (self.isAutoScroll) {
        self.scrollView.contentSize = CGSizeMake(self.frame.size.width * (self.imageAry.count + 2), 0);
        self.scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
    }else{
        self.scrollView.contentSize = CGSizeMake(self.frame.size.width * self.imageAry.count, 0);
    }
    
}


/** 创建定时器
 *
 */
-(void)createTimer{
    self.timer = [NSTimer  scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}


/**
 *
 */
-(void)createPageView{
    
    self.pageControl = [[YAYIPageControl alloc] init];
    self.pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];;

    self.pageControl.numberOfPages = self.imageAry.count;
    self.pageControl.frame = CGRectMake(0, 0, 100, 20);
    self.pageControl.center = CGPointMake(self.width * 0.5, self.height - 15);
    [self addSubview:self.pageControl];
}


-(void)timerAction:(NSTimer *)timer{
    
    CGPoint offset = self.scrollView.contentOffset;
    offset.x += self.scrollView.frame.size.width;
    [self.scrollView setContentOffset:offset animated:YES];
}




#pragma mark - 定时器控制
- (void)startTimer
{
    // 创建一个定时器
    if (self.timer == nil) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    
}

- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

/**
 * 下一页
 */
- (void)nextPage
{
    CGFloat scrollWidth = self.scrollView.frame.size.width;
    NSInteger index = self.pageControl.currentPage;
    if (index == self.imageAry.count + 1) {
        index = 0;
    } else {
        index ++;
    }
    [self.scrollView setContentOffset:CGPointMake((index + 1) * scrollWidth, 0) animated:YES];
}


#pragma mark - 代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat scrollWidth = self.scrollView.frame.size.width;
    NSInteger index = (self.scrollView.contentOffset.x + scrollWidth * 0.5) / scrollWidth;
    if (self.isAutoScroll) {
        if (index == self.imageAry.count + 2) {
            index = 1;
        } else if (index == 0) {
            index = self.imageAry.count ;
        }
        self.pageControl.currentPage = index - 1;
    }else{
    
        self.pageControl.currentPage = index;
    }
    
    
}


- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    //此方法，
    [self scrollViewFinish:scrollView];
}

/**
 *  滚动视图减速完成,滚动将停止时,调用该方法。一次有效滑动,只执行一次。
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewFinish:scrollView];
}

- (void)scrollViewFinish:(UIScrollView *)scrollView
{
    CGFloat scrollWidth = self.scrollView.frame.size.width;
    NSInteger index = (self.scrollView.contentOffset.x + scrollWidth * 0.5) / scrollWidth;
    if (self.isAutoScroll) {
        
        if (index == self.imageAry.count + 1) {
            //显示最后一张的时候，强制设置为第二张（也就是轮播图的第一张），这样就开始无限循环了
            [self.scrollView setContentOffset:CGPointMake(scrollWidth, 0) animated:NO];
        } else if (index == 0) {
            //显示第一张的时候，强制设置为倒数第二张（轮播图最后一张），实现倒序无限循环
            [self.scrollView setContentOffset:CGPointMake(self.imageAry.count * scrollWidth, 0) animated:NO];
        }
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.isAutoScroll) {
        
        [self startTimer];
    }
}


@end
